import network
import socket
import time
from machine import Pin
import gc
import _thread
from dns_server import DNSServer
from web_server import WebServer

# 配置AP模式
def setup_ap():
    """设置ESP32为AP模式"""
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid='ESP32_DNS_Server', password='12345678', authmode=network.AUTH_WPA_WPA2_PSK)
    
    # 设置静态IP
    ap.ifconfig(('192.168.4.1', '255.255.255.0', '192.168.4.1', '8.8.8.8'))
    
    print("AP模式已启动")
    print(f"SSID: ESP32_DNS_Server")
    print(f"密码: 12345678")
    print(f"IP地址: {ap.ifconfig()[0]}")
    
    return ap

def start_dns_server():
    """启动DNS服务器"""
    dns_server = DNSServer()
    dns_server.start()

def start_web_server():
    """启动Web服务器"""
    web_server = WebServer()
    web_server.start()

def main():
    """主函数"""
    print("启动ESP32 DNS服务器...")
    
    # 设置AP模式
    ap = setup_ap()
    
    # 等待AP完全启动
    time.sleep(2)
    
    print("DNS服务器已启动，监听端口53...")
    print("Web服务器已启动，监听端口80...")
    print("连接到ESP32_DNS_Server网络，DNS服务器地址为192.168.4.1")
    print("访问 http://192.168.4.1 查看管理界面")
    
    try:
        # 在新线程中启动DNS服务器
        _thread.start_new_thread(start_dns_server, ())
        
        # 在主线程中启动Web服务器
        start_web_server()
        
    except KeyboardInterrupt:
        print("正在停止服务器...")
        ap.active(False)
        print("服务器已停止")

if __name__ == "__main__":
    main() 